package cn.wolfcode.mp.service.impl;

import cn.wolfcode.mp.domain.Permission;
import cn.wolfcode.mp.mapper.PermissionMapper;
import cn.wolfcode.mp.service.IPermissionService;
import cn.wolfcode.mp.util.RequiredPermission;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public void load() {
        List<String> expressionString2 = this.selectAllExpression();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        Collection<HandlerMethod> handMethods = handlerMethods.values();
        for (HandlerMethod handMethod : handMethods) {
            RequiredPermission requiredPermission = handMethod.getMethodAnnotation(RequiredPermission.class);
            if (requiredPermission != null) {
                //获取注解中的 name 值
                String name = requiredPermission.name();
                //获取注解中的 expression 值
                String expression = requiredPermission.expression();
                //创建权限对象,将参数封装进去
                Permission permission = new Permission();
                permission.setName(name);
                permission.setExpression(expression);
                //判断数据库中是否存在
                if (!expressionString2.contains(expression)) {  //不存在时新增
                    super.save(permission);
                    //新增之后还需要添加到集合中更新
                    expressionString2.add(expression);
                }
            }
        }


    }

    private List<String> selectAllExpression() {
        ArrayList<String> strings = new ArrayList<>();
        List<Permission> list = super.list();
        for (Permission permission : list) {
            String expression = permission.getExpression();
            strings.add(expression);
        }
        return strings;
    }
}
